import React, {
  useState,
  useEffect,
  useCallback,
  useMemo,
  useRef,
} from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/components/ui/use-toast";
import {
  Save,
  Calculator,
  Ruler,
  Maximize,
  Cable,
  Trash2,
  Zap,
  Plus,
  ChevronDown,
  ChevronRight,
  X,
} from "lucide-react";
import { TooltipProvider } from "@/components/ui/tooltip";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { ConductorSpecAPI } from "@/api/ConductorSpec";
import { TensionSectionAPI } from "@/api/tensionSection";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import { CrossingPointAPI } from "@/api/CrossingPoint";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import FormulaDisplay from "../FormulaDisplay";

// 单个绝缘绳网计算器组件
const SingleNettingCalculator = ({
  nettingItem,
  onUpdate,
  onRemove,
  crossingPoint, // 原有的 crossingPoint
  crossingPointData, // 新增：当前跨越点的详细数据
  scheme,
  allWindOffsets,
  index,
}) => {
  console.log(`===== SingleNettingCalculator (索引: ${index}) 初始化 =====`);
  const [isExpanded, setIsExpanded] = useState(index === 0);
  const [isWeightDetailsOpen, setIsWeightDetailsOpen] = useState(false);

  // 步骤1.1: 计算到塔的水平距离 - 使用当前跨越点的数据
  const calculatedHorizontalDistanceToTower = useMemo(() => {
    console.log(`步骤1.1: 计算到塔的水平距离 (索引: ${index})`);
    
    // 优先使用当前跨越点的数据
    const currentCrossingPoint = crossingPointData || crossingPoint;
    const leftDistance = currentCrossingPoint?.towerLeft?.distanceToRoad;
    const rightDistance = currentCrossingPoint?.towerRight?.distanceToRoad;
    const isValidDistance = (dist) =>
      typeof dist === "number" && !isNaN(dist) && dist >= 0;

    console.log(
      `步骤1.1参数: 左塔距离=${leftDistance}, 右塔距离=${rightDistance}`
    );
    
    if (isValidDistance(leftDistance) && isValidDistance(rightDistance)) {
      const result = Math.min(leftDistance, rightDistance);
      console.log(`步骤1.1结果: 最小距离=${result}`);
      return result;
    }
    
    const result = isValidDistance(leftDistance)
      ? leftDistance
      : isValidDistance(rightDistance)
      ? rightDistance
      : 0;
    console.log(`步骤1.1结果: ${result} (使用可用值或默认0)`);
    return result;
  }, [crossingPointData, crossingPoint, index]);

  // 步骤1.2: 整合本地计算参数 - 使用当前跨越点的数据
  const localParams = useMemo(() => {
    console.log(`步骤1.2: 整合本地计算参数 (索引: ${index})`);
    
    // 优先使用当前跨越点的数据
    const currentCrossingPoint = crossingPointData || crossingPoint;
    const params = {
      spanLength: currentCrossingPoint?.spanLength ?? 0,
      designWindPressure:
        scheme.designWindPressure ?? currentCrossingPoint?.designWindPressure ?? 0.5,
      horizontalDistanceToTower: calculatedHorizontalDistanceToTower,
      conductorHorizontalTension: scheme.nettingConductorTension ?? 10000,
      insulatorStringLength: scheme.nettingInsulatorStringLength ?? 10,
    };
    console.log(`步骤1.2参数集合:`, params);
    return params;
  }, [crossingPointData, crossingPoint, scheme, calculatedHorizontalDistanceToTower, index]);

  const handleItemChange = (field, value) => {
    console.log(`步骤1.3: 更新字段 ${field}=${value} (索引: ${index})`);
    onUpdate(nettingItem.id, { ...nettingItem, [field]: value });
  };

  const handleNumberChange = (field, value) => {
    const numValue = parseFloat(value);
    const processed = isNaN(numValue) ? 0 : numValue;
    console.log(`步骤1.4: 更新数字字段 ${field}=${processed} (索引: ${index})`);
    handleItemChange(field, processed);
  };

  // 步骤1.5: 计算绝缘绳网自身重量
  const nettingItemWeight = useMemo(() => {
    console.log(`步骤1.5: 计算绝缘绳网重量 (索引: ${index})`);
    const {
      nettingInsulatorRodCount = 0,
      nettingInsulatorRodLength = 0,
      nettingInsulatorRodUnitWeight = 0,
      nettingRopeCount = 0,
      nettingRopeLength = 0,
      nettingRopeUnitWeight = 0,
      nettingAttachmentTotalWeight = 0,
    } = nettingItem;

    console.log(`步骤1.5参数:`, {
      绝缘杆数量: nettingInsulatorRodCount,
      绝缘杆长度: nettingInsulatorRodLength,
      绝缘杆单重: nettingInsulatorRodUnitWeight,
      绳数量: nettingRopeCount,
      绳长度: nettingRopeLength,
      绳单重: nettingRopeUnitWeight,
      附件总重: nettingAttachmentTotalWeight,
    });

    const g = 9.8;
    const totalInsulatorRodWeightKg =
      nettingInsulatorRodCount *
      nettingInsulatorRodLength *
      nettingInsulatorRodUnitWeight;
    const totalNettingRopeWeightKg =
      nettingRopeCount * nettingRopeLength * nettingRopeUnitWeight;
    const totalAttachmentWeightKg = nettingAttachmentTotalWeight;

    const totalWeightKg =
      totalInsulatorRodWeightKg +
      totalNettingRopeWeightKg +
      totalAttachmentWeightKg;
    const result = totalWeightKg * g;
    console.log(`步骤1.5结果: 总重=${result.toFixed(2)}N`);
    return result;
  }, [nettingItem, index]);

  // 步骤1.6: 计算最大风偏
  const currentMaxWindOffset = useMemo(() => {
    console.log(`步骤1.6: 计算最大风偏 (索引: ${index})`);
    console.log(`步骤1.6输入风偏数据:`, allWindOffsets);

    const validOffsets = allWindOffsets.filter((r) => {
      if (!r.isValid) {
        console.warn(`步骤1.6无效数据: ${r.name} - ${r.error || "未知错误"}`);
      }
      return r.isValid;
    });

    console.log(
      `步骤1.6有效风偏:`,
      validOffsets.map((o) => ({ name: o.name, value: o.windOffset }))
    );
    const max =
      validOffsets.length > 0
        ? Math.max(...validOffsets.map((r) => parseFloat(r.windOffset)))
        : 0;
    console.log(`步骤1.6结果: 最大风偏=${max}`);

    if (max <= 0) {
      console.error(`步骤1.6警告: 最大风偏≤0，可能导致计算错误`);
    }
    return max;
  }, [allWindOffsets, index]);

  // 步骤1.7: 计算最终尺寸结果
  const finalResults = useMemo(() => {
    console.log(`步骤1.7: 计算最终尺寸 (索引: ${index})`);
    console.log(
      `步骤1.7参数: 最大风偏=${currentMaxWindOffset}, 绳网参数=`,
      nettingItem
    );

    if (currentMaxWindOffset <= 0) {
      console.error(`步骤1.7错误: 最大风偏≤0，无法计算`);
      return {
        hasError: true,
        errorMessage: "无法计算最大风偏。",
        calculatedWidth: null,
        calculatedLength: null,
      };
    }

    try {
      const calculatedWidth =
        2 * currentMaxWindOffset +
        nettingItem.crossedObjectWidth +
        2 * nettingItem.nettingSafetyClearance;
      console.log(
        `步骤1.7宽度计算: 2*${currentMaxWindOffset} + ${nettingItem.crossedObjectWidth} + 2*${nettingItem.nettingSafetyClearance} = ${calculatedWidth}`
      );

      const crossingAngleRad = (nettingItem.crossingAngle * Math.PI) / 180;
      if (Math.abs(Math.sin(crossingAngleRad)) < 1e-6) {
        throw new Error("交叉角度不能为0°或180°。");
      }

      const calculatedLength =
        nettingItem.crossedObjectWidth / Math.sin(crossingAngleRad) +
        calculatedWidth / Math.tan(crossingAngleRad) +
        2 * nettingItem.nettingExtensionLength;
      console.log(
        `步骤1.7长度计算: ${nettingItem.crossedObjectWidth}/sin(${nettingItem.crossingAngle}°) + ${calculatedWidth}/tan(${nettingItem.crossingAngle}°) + 2*${nettingItem.nettingExtensionLength} = ${calculatedLength}`
      );

      const result = {
        hasError: false,
        calculatedWidth: calculatedWidth.toFixed(2),
        calculatedLength: calculatedLength.toFixed(2),
        maxWindOffset: currentMaxWindOffset.toFixed(2),
      };
      console.log(`步骤1.7结果:`, result);
      return result;
    } catch (error) {
      console.error(`步骤1.7计算错误:`, error.message);
      return {
        hasError: true,
        errorMessage: `计算尺寸出错: ${error.message}`,
        calculatedWidth: null,
        calculatedLength: null,
      };
    }
  }, [currentMaxWindOffset, nettingItem, index]);

  // 步骤1.8: 自动更新计算结果到父组件
  useEffect(() => {
    console.log(`步骤1.8: 检查是否需要更新父组件 (索引: ${index})`);
    if (!finalResults.hasError) {
      const newCalculatedWidth = parseFloat(finalResults.calculatedWidth);
      const newCalculatedLength = parseFloat(finalResults.calculatedLength);
      const newMaxWindOffset = parseFloat(finalResults.maxWindOffset);

      if (
        nettingItem.calculatedWidth !== newCalculatedWidth ||
        nettingItem.calculatedLength !== newCalculatedLength ||
        nettingItem.maxWindOffset !== newMaxWindOffset
      ) {
        console.log(`步骤1.8更新:`, {
          calculatedWidth: newCalculatedWidth,
          calculatedLength: newCalculatedLength,
          maxWindOffset: newMaxWindOffset,
        });
        onUpdate(nettingItem.id, {
          ...nettingItem,
          calculatedWidth: newCalculatedWidth,
          calculatedLength: newCalculatedLength,
          maxWindOffset: newMaxWindOffset,
        });
      } else {
        console.log(`步骤1.8: 计算结果无变化，无需更新`);
      }
    } else {
      console.log(`步骤1.8: 计算有错误，不更新`);
    }
  }, [finalResults, nettingItem, onUpdate, index]);

  return (
    <Card className="overflow-hidden">
      <CardHeader
        className="flex flex-row items-center justify-between p-3 bg-gray-50 cursor-pointer"
        onClick={() => setIsExpanded(!isExpanded)}
      >
        <div className="flex items-center gap-2">
          {isExpanded ? (
            <ChevronDown className="w-4 h-4" />
          ) : (
            <ChevronRight className="w-4 h-4" />
          )}
          <Input
            value={nettingItem.name}
            onChange={(e) => handleItemChange("name", e.target.value)}
            onClick={(e) => e.stopPropagation()}
            className="h-8 font-medium border-0 shadow-none focus-visible:ring-1 focus-visible:ring-ring"
            placeholder="输入跨越对象名称"
          />
        </div>
        <div className="flex items-center gap-2">
          {finalResults.hasError ? (
            <Badge variant="destructive">错误</Badge>
          ) : (
            <Badge variant="secondary">
              宽: {finalResults.calculatedWidth}m, 长:{" "}
              {finalResults.calculatedLength}m
            </Badge>
          )}
          <Button
            variant="ghost"
            size="icon"
            className="w-8 h-8"
            onClick={(e) => {
              e.stopPropagation();
              onRemove(nettingItem.id);
            }}
          >
            <X className="w-4 h-4 text-red-500" />
          </Button>
        </div>
      </CardHeader>
      {isExpanded && (
        <CardContent className="p-4 space-y-4">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            <div>
              <Label className="text-xs">被跨物宽度 (m)</Label>
              <Input
                type="number"
                step="0.1"
                value={nettingItem.crossedObjectWidth}
                onChange={(e) =>
                  handleNumberChange("crossedObjectWidth", e.target.value)
                }
                className="h-8"
              />
            </div>
            <div>
              <Label className="text-xs">交叉角度 (°)</Label>
              <Input
                type="number"
                step="1"
                min="1"
                max="179"
                value={nettingItem.crossingAngle}
                onChange={(e) =>
                  handleNumberChange("crossingAngle", e.target.value)
                }
                className="h-8"
              />
            </div>
            <div>
              <Label className="text-xs">安全净距 (m)</Label>
              <Input
                type="number"
                step="0.1"
                value={nettingItem.nettingSafetyClearance}
                onChange={(e) =>
                  handleNumberChange("nettingSafetyClearance", e.target.value)
                }
                className="h-8"
              />
            </div>
            <div>
              <Label className="text-xs">封网延伸长度 (m)</Label>
              <Input
                type="number"
                step="1"
                value={nettingItem.nettingExtensionLength}
                onChange={(e) =>
                  handleNumberChange("nettingExtensionLength", e.target.value)
                }
                className="h-8"
              />
            </div>
          </div>

          <Collapsible
            open={isWeightDetailsOpen}
            onOpenChange={setIsWeightDetailsOpen}
          >
            <CollapsibleTrigger asChild>
              <Button
                variant="link"
                className="p-0 h-auto text-blue-600 text-xs"
              >
                <ChevronDown
                  className={`w-3 h-3 mr-1 transition-transform ${
                    isWeightDetailsOpen ? "rotate-180" : ""
                  }`}
                />
                此绝缘绳网重量配置
              </Button>
            </CollapsibleTrigger>
            <CollapsibleContent className="pt-2 space-y-2">
              <div className="grid grid-cols-2 gap-2 text-xs">
                <div>
                  <Label className="text-xs">绝缘杆数量 (根)</Label>
                  <Input
                    type="number"
                    min="0"
                    value={nettingItem.nettingInsulatorRodCount ?? ""}
                    onChange={(e) =>
                      handleNumberChange(
                        "nettingInsulatorRodCount",
                        e.target.value
                      )
                    }
                    className="h-7"
                  />
                </div>
                <div>
                  <Label className="text-xs">杆长度 (m/根)</Label>
                  <Input
                    type="number"
                    step="0.1"
                    min="0"
                    value={nettingItem.nettingInsulatorRodLength ?? ""}
                    onChange={(e) =>
                      handleNumberChange(
                        "nettingInsulatorRodLength",
                        e.target.value
                      )
                    }
                    className="h-7"
                  />
                </div>
                <div>
                  <Label className="text-xs">杆单重 (kg/m)</Label>
                  <Input
                    type="number"
                    step="0.1"
                    min="0"
                    value={nettingItem.nettingInsulatorRodUnitWeight ?? ""}
                    onChange={(e) =>
                      handleNumberChange(
                        "nettingInsulatorRodUnitWeight",
                        e.target.value
                      )
                    }
                    className="h-7"
                  />
                </div>
                <div>
                  <Label className="text-xs">绳数量 (根)</Label>
                  <Input
                    type="number"
                    min="0"
                    value={nettingItem.nettingRopeCount ?? ""}
                    onChange={(e) =>
                      handleNumberChange("nettingRopeCount", e.target.value)
                    }
                    className="h-7"
                  />
                </div>
                <div>
                  <Label className="text-xs">绳长度 (m/根)</Label>
                  <Input
                    type="number"
                    step="0.1"
                    min="0"
                    value={nettingItem.nettingRopeLength ?? ""}
                    onChange={(e) =>
                      handleNumberChange("nettingRopeLength", e.target.value)
                    }
                    className="h-7"
                  />
                </div>
                <div>
                  <Label className="text-xs">绳单重 (kg/m)</Label>
                  <Input
                    type="number"
                    step="0.1"
                    min="0"
                    value={nettingItem.nettingRopeUnitWeight ?? ""}
                    onChange={(e) =>
                      handleNumberChange(
                        "nettingRopeUnitWeight",
                        e.target.value
                      )
                    }
                    className="h-7"
                  />
                </div>
                <div className="col-span-2">
                  <Label className="text-xs">附件总重 (kg)</Label>
                  <Input
                    type="number"
                    step="0.1"
                    min="0"
                    value={nettingItem.nettingAttachmentTotalWeight ?? ""}
                    onChange={(e) =>
                      handleNumberChange(
                        "nettingAttachmentTotalWeight",
                        e.target.value
                      )
                    }
                    className="h-7"
                  />
                </div>
              </div>
            </CollapsibleContent>
          </Collapsible>

          <div className="p-2 bg-slate-50 rounded border text-center">
            <Label className="text-xs font-medium">此绝缘绳网总重</Label>
            <div className="text-sm font-bold text-slate-800">
              {nettingItemWeight.toFixed(2)} N
            </div>
          </div>

          {!finalResults.hasError ? (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3 pt-2">
              <div className="p-2 bg-blue-50 rounded-lg border border-blue-200 text-center">
                <div className="text-xs text-blue-600 font-medium">
                  最大风偏
                </div>
                <div className="text-lg font-bold text-blue-800">
                  {finalResults.maxWindOffset} m
                </div>
              </div>
              <div className="p-2 bg-green-50 rounded-lg border border-green-200 text-center">
                <div className="text-xs text-green-600 font-medium">
                  计算宽度
                </div>
                <div className="text-lg font-bold text-green-800">
                  {finalResults.calculatedWidth} m
                </div>
              </div>
              <div className="p-2 bg-purple-50 rounded-lg border border-purple-200 text-center">
                <div className="text-xs text-purple-600 font-medium">
                  计算长度
                </div>
                <div className="text-lg font-bold text-purple-800">
                  {finalResults.calculatedLength} m
                </div>
              </div>
            </div>
          ) : (
            <div className="text-center py-4 text-red-500 border border-dashed border-red-300 rounded-lg text-sm">
              {finalResults.errorMessage}
            </div>
          )}
        </CardContent>
      )}
    </Card>
  );
};

// 主组件
export default function InsulationNettingCalculator({
  scheme,
  onUpdate,
  crossingPoint: initialCrossingPoint,
  crossingPointList, // 新增：接收 crossingPointList
}) {
  console.log("===== 主组件 InsulationNettingCalculator 初始化 =====");
  console.log("传入的 crossingPointList:", crossingPointList);

  const { toast } = useToast();
  const [allConductorSpecs, setAllConductorSpecs] = useState([]);
  const [conductorSpec, setConductorSpec] = useState(null);
  const [isLoadingConductorSpec, setIsLoadingConductorSpec] = useState(true);
  const [conductorType, setConductorType] = useState(
    scheme.insulband?.parametersWire?.conductorType ??
      initialCrossingPoint?.conductorType
  );
  const [conductorHorizontalTension, setConductorHorizontalTension] = useState(
    scheme.insulband?.parametersWire?.conductorHorizontalTension ?? 10000
  );
  const [insulatorStringLength, setInsulatorStringLength] = useState(
    scheme.insulband?.parametersWire?.insulatorStringLength ?? 10
  );

  // 使用 crossingPointList 作为主要数据源
  const [crossingPoints, setCrossingPoints] = useState(crossingPointList || []);
  
  // 步骤2: 初始化绝缘绳网列表 - 基于 crossingPointList
  const [multipleNettings, setMultipleNettings] = useState(() => {
    console.log("步骤2: 初始化绝缘绳网列表");
    
    // 优先使用 crossingPointList 中的数据
    if (crossingPointList && crossingPointList.length > 0) {
      console.log("步骤2: 使用 crossingPointList 数据创建绝缘绳网项");
      return crossingPointList.map((cp, index) => ({
        id: cp.id || `netting-${index}`,
        name: cp.name || `跨越点 ${index + 1}`,
        crossedObjectWidth: cp.crossedObjectWidth || 0,
        crossingAngle: cp.crossingAngle || 90,
        nettingSafetyClearance: scheme.nettingSafetyClearance ?? 0,
        nettingExtensionLength: scheme.nettingExtensionLength ?? 0,
        calculatedWidth: null,
        calculatedLength: null,
        maxWindOffset: null,
        // 重量相关字段
        nettingInsulatorRodCount: 0,
        nettingInsulatorRodLength: 0,
        nettingInsulatorRodUnitWeight: 0,
        nettingRopeCount: 0,
        nettingRopeLength: 0,
        nettingRopeUnitWeight: 0,
        nettingAttachmentTotalWeight: 0,
      }));
    }
    
    // 如果没有 crossingPointList，回退到 scheme 中的数据
    const initial = scheme.insulband?.multipleNettings || [];
    console.log("步骤2: 回退到 scheme 数据:", initial);
    return initial;
  });

  // 监听 crossingPointList 的变化
  useEffect(() => {
    if (crossingPointList && crossingPointList.length > 0) {
      console.log("检测到 crossingPointList 更新，同步数据");
      setCrossingPoints(crossingPointList);
      
      // 如果 crossingPointList 有数据但 multipleNettings 为空，自动创建
      if (multipleNettings.length === 0) {
        const newNettings = crossingPointList.map((cp, index) => ({
          id: cp.id || `netting-${Date.now()}-${index}`,
          name: cp.name || `跨越点 ${index + 1}`,
          crossedObjectWidth: cp.crossedObjectWidth || 0,
          crossingAngle: cp.crossingAngle || 90,
          nettingSafetyClearance: scheme.nettingSafetyClearance ?? 2,
          nettingExtensionLength: scheme.nettingExtensionLength ?? 5,
          calculatedWidth: null,
          calculatedLength: null,
          maxWindOffset: null,
          nettingInsulatorRodCount: 0,
          nettingInsulatorRodLength: 0,
          nettingInsulatorRodUnitWeight: 0,
          nettingRopeCount: 0,
          nettingRopeLength: 0,
          nettingRopeUnitWeight: 0,
          nettingAttachmentTotalWeight: 0,
        }));
        setMultipleNettings(newNettings);
      }
    }
  }, [crossingPointList, scheme, multipleNettings.length]);

  // 步骤3: 初始化其他线路组件
  const [otherLineComponents, setOtherLineComponents] = useState(() => {
    console.log("步骤3: 初始化其他线路组件");
    const savedComponents = scheme.insulband?.otherLineComponents;
    if (Array.isArray(savedComponents) && savedComponents.length > 0) {
      const processed = savedComponents.map((comp) => {
        const result = comp.id
          ? comp
          : {
              ...comp,
              id: `other-line-${Date.now()}-${Math.random()
                .toString(36)
                .substring(2, 9)}`,
            };
        return result;
      });
      console.log("步骤3处理后的数据:", processed);
      return processed;
    }
    console.log("步骤3: 无保存的线路组件，初始化为空数组");
    return [];
  });

  // 步骤4: 加载导线规格数据
  useEffect(() => {
    const loadConductorSpecs = async () => {
      console.log("步骤4: 开始加载导线规格列表");
      if (!ConductorSpecAPI) {
        console.error("步骤4错误: ConductorSpecAPI 未定义");
        setAllConductorSpecs([]);
        return;
      }
      try {
        const specs = await ConductorSpecAPI.getList();
        console.log("步骤4: 接口返回结果:", specs);
        const data = Array.isArray(specs.data) ? specs.data : [];
        console.log("步骤4: 处理后的导线规格列表（长度：", data.length, "）");
        setAllConductorSpecs(data);
      } catch (error) {
        console.error("步骤4错误: 加载导线规格失败", error);
        setAllConductorSpecs([]);
      }
    };
    loadConductorSpecs();
  }, []);

  // 步骤5: 加载选中的导线规格
  useEffect(() => {
    console.log("步骤5: 解析选中的导线规格");
    console.log("步骤5参数: conductorType=", conductorType, "allConductorSpecs长度=", allConductorSpecs.length);
    setIsLoadingConductorSpec(true);

    if (conductorType && allConductorSpecs.length > 0) {
      const selectedSpec = allConductorSpecs.find(
        (s) => s.model === conductorType
      );
      if (selectedSpec) {
        console.log("步骤5: 找到匹配的导线规格", selectedSpec);
        setConductorSpec(selectedSpec);
      } else {
        console.warn("步骤5: 未找到匹配的导线规格，型号=", conductorType);
        setConductorSpec(null);
      }
    } else {
      console.log("步骤5: 缺少导线型号或规格列表为空");
      setConductorSpec(null);
    }
    setIsLoadingConductorSpec(false);
  }, [conductorType, allConductorSpecs]);

  const addNettingObject = () => {
    console.log("步骤6: 添加新的绝缘绳网对象");
    const newItem = {
      id: `netting-${Date.now()}`,
      name: `新增跨越对象 ${multipleNettings.length + 1}`,
      crossedObjectWidth: 0,
      crossingAngle: 90,
      nettingSafetyClearance: 2,
      nettingExtensionLength: 5,
      calculatedWidth: null,
      calculatedLength: null,
      maxWindOffset: null,
      nettingInsulatorRodCount: 0,
      nettingInsulatorRodLength: 0,
      nettingInsulatorRodUnitWeight: 0,
      nettingRopeCount: 0,
      nettingRopeLength: 0,
      nettingRopeUnitWeight: 0,
      nettingAttachmentTotalWeight: 0,
    };
    console.log("步骤6新增对象:", newItem);
    setMultipleNettings((prev) => [...prev, newItem]);
  };

  const updateNettingObject = (id, updatedItem) => {
    console.log(`步骤7: 更新绝缘绳网 (ID: ${id})`, updatedItem);
    setMultipleNettings((prev) =>
      prev.map((item) => (item.id === id ? updatedItem : item))
    );
  };

  const removeNettingObject = (id) => {
    console.log(`步骤8: 删除绝缘绳网 (ID: ${id})`);
    setMultipleNettings((prev) => prev.filter((item) => item.id !== id));
  };

  const addOtherLineComponent = () => {
    console.log("步骤9: 添加新的线路组件");
    const newComponent = {
      id: `other-line-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
      name: `线路${otherLineComponents.length + 1}`,
      outerDiameter: 20,
      weightPerMeter: 15,
      windLoadShapeFactor: 1.1,
      stringLength: 0,
      horizontalTension: 5000,
    };
    console.log("步骤9新增组件:", newComponent);
    setOtherLineComponents((prev) => [...prev, newComponent]);
  };

  const removeOtherLineComponent = (id) => {
    console.log(`步骤10: 删除线路组件 (ID: ${id})`);
    setOtherLineComponents((prev) => prev.filter((comp) => comp.id !== id));
  };

  const updateOtherLineComponent = (id, field, value) => {
    const numericFields = [
      "outerDiameter",
      "weightPerMeter",
      "stringLength",
      "horizontalTension",
      "windLoadShapeFactor",
    ];
    let processedValue = value;
    if (numericFields.includes(field)) {
      const numValue = parseFloat(value);
      processedValue = isNaN(numValue) ? 0 : numValue;
    }
    console.log(`步骤11: 更新线路组件 (ID: ${id}) 字段 ${field}=${processedValue}`);
    setOtherLineComponents((prev) =>
      prev.map((comp) =>
        comp.id === id ? { ...comp, [field]: processedValue } : comp
      )
    );
  };

  // 步骤12: 计算所有组件的风偏
  const allWindOffsets = useMemo(() => {
    console.log("步骤12: 计算所有组件的风偏");
    const results = [];

    if (conductorSpec && !isLoadingConductorSpec) {
      console.log("步骤12: 开始计算导线风偏");
      const conductorParams = {
        outerDiameter: conductorSpec.outerDiameterMm,
        weightPerMeter: conductorSpec.weightPerMeterNPerM,
        stringLength: insulatorStringLength,
        horizontalTension: conductorHorizontalTension,
      };
      console.log("步骤12导线参数:", conductorParams);

      // 校验导线参数
      const missingParams = [];
      if (conductorParams.outerDiameter === undefined || conductorParams.outerDiameter <= 0)
        missingParams.push("outerDiameter（导线外径）");
      if (conductorParams.weightPerMeter === undefined || conductorParams.weightPerMeter <= 0)
        missingParams.push("weightPerMeter（单位重量）");
      if (conductorParams.horizontalTension === undefined || conductorParams.horizontalTension <= 0)
        missingParams.push("horizontalTension（水平张力）");

      if (missingParams.length > 0) {
        console.error(`步骤12错误: 导线参数缺失 - ${missingParams.join(", ")}`);
        results.push({
          name: `导线 (${conductorType})`,
          type: "conductor",
          isValid: false,
          error: `参数缺失: ${missingParams.join(", ")}`,
          windOffsetValue: -1,
        });
      } else {
        // 计算导线风偏
        const calculateWindOffsetInternal = (params) => {
          // 使用第一个跨越点的杆塔距离作为参考
          const towerDistance = crossingPoints[0]?.towerLeft?.distanceToRoad || 0;
          const spanLength = crossingPoints[0]?.spanLength ?? 0;
          console.log(`步骤12导线计算参数: 杆塔距离=${towerDistance}, 档距长度=${spanLength}`);

          // 校验外部参数
          if (towerDistance <= 0)
            return { isValid: false, error: "杆塔距离必须大于0" };
          if (spanLength <= 0)
            return { isValid: false, error: "档距长度必须大于0" };

          try {
            const windLoadShapeFactor = 1.1;
            const W4 = 0.0613 * windLoadShapeFactor * params.outerDiameter;
            console.log(`步骤12: 风荷载W4=${W4}`);

            const term1 = (towerDistance * (spanLength - towerDistance)) / (2 * params.horizontalTension);
            const term2 = params.stringLength / params.weightPerMeter;
            console.log(`步骤12: 中间项 term1=${term1}, term2=${term2}`);

            const Zx = W4 * (term1 + term2);
            console.log(`步骤12: 导线风偏计算结果=${Zx}`);
            return {
              isValid: true,
              windOffset: Zx > 0 ? Zx.toFixed(2) : 0,
              debug: { W4, term1, term2, Zx },
            };
          } catch (error) {
            console.error("步骤12导线计算错误:", error);
            return { isValid: false, error: error.message };
          }
        };

        const conductorResult = calculateWindOffsetInternal(conductorParams);
        results.push({
          name: `导线 (${conductorType})`,
          type: "conductor",
          ...conductorResult,
          windOffsetValue: conductorResult.isValid ? parseFloat(conductorResult.windOffset) : -1,
        });
      }
    } else {
      console.log("步骤12: 导线规格未加载或加载中，跳过导线风偏计算");
    }

    // 计算其他线路组件的风偏
    otherLineComponents.forEach((component, idx) => {
      console.log(`步骤12: 计算其他线路组件风偏 (索引: ${idx})`);
      const componentParams = {
        outerDiameter: component.outerDiameter,
        weightPerMeter: component.weightPerMeter,
        stringLength: component.stringLength,
        horizontalTension: component.horizontalTension,
      };
      console.log(`步骤12组件参数:`, componentParams);

      // 校验组件参数
      const missingParams = [];
      if (componentParams.outerDiameter === undefined || componentParams.outerDiameter <= 0)
        missingParams.push("outerDiameter（外径）");
      if (componentParams.weightPerMeter === undefined || componentParams.weightPerMeter <= 0)
        missingParams.push("weightPerMeter（单位重量）");
      if (componentParams.horizontalTension === undefined || componentParams.horizontalTension <= 0)
        missingParams.push("horizontalTension（张力）");

      if (missingParams.length > 0) {
        console.error(`步骤12错误: 组件 ${component.name} 参数缺失 - ${missingParams.join(", ")}`);
        results.push({
          name: component.name,
          type: "other-component",
          isValid: false,
          error: `参数缺失: ${missingParams.join(", ")}`,
          windOffsetValue: -1,
        });
        return;
      }

      // 计算组件风偏
      const towerDistance = crossingPoints[0]?.towerLeft?.distanceToRoad ?? 0;
      const spanLength = crossingPoints[0]?.spanLength ?? 0;
      console.log(`步骤12组件计算参数: 杆塔距离=${towerDistance}, 档距长度=${spanLength}`);

      if (towerDistance <= 0) {
        results.push({
          name: component.name,
          type: "other-component",
          isValid: false,
          error: "杆塔距离必须大于0",
          windOffsetValue: -1,
        });
        return;
      }
      if (spanLength <= 0) {
        results.push({
          name: component.name,
          type: "other-component",
          isValid: false,
          error: "档距长度必须大于0",
          windOffsetValue: -1,
        });
        return;
      }

      try {
        const windLoadShapeFactor = 1.1;
        const W4 = 0.0613 * windLoadShapeFactor * componentParams.outerDiameter;
        const Zx =
          W4 *
          ((towerDistance * (spanLength - towerDistance)) / (2 * componentParams.horizontalTension) +
            componentParams.stringLength / componentParams.weightPerMeter);
        console.log(`步骤12: 组件 ${component.name} 风偏计算结果=${Zx}`);

        results.push({
          name: component.name,
          type: "other-component",
          isValid: true,
          windOffset: Zx > 0 ? Zx.toFixed(2) : 0,
          windOffsetValue: Zx > 0 ? Zx : -1,
        });
      } catch (error) {
        console.error(`步骤12组件计算错误:`, error);
        results.push({
          name: component.name,
          type: "other-component",
          isValid: false,
          error: error.message,
          windOffsetValue: -1,
        });
      }
    });

    console.log("步骤12: 所有风偏计算结果", results);
    return results;
  }, [conductorSpec, isLoadingConductorSpec, conductorType, conductorHorizontalTension, insulatorStringLength, otherLineComponents, crossingPoints]);

  const handleSave = useCallback(() => {
    console.log("步骤13: 开始保存所有计算结果");
    // 检查是否有错误
    const hasErrors = multipleNettings.some(
      (item) => !item.calculatedWidth || !item.calculatedLength
    );
    if (hasErrors) {
      console.error("步骤13错误: 存在计算错误，保存失败");
      toast({
        variant: "destructive",
        title: "保存失败",
        description: "存在计算错误或未完成的绝缘绳网计算。",
      });
      return;
    }

    console.log("步骤13: 准备保存的数据");
    const saveData = {
      conductorType: conductorType,
      nettingConductorTension: parseFloat(conductorHorizontalTension),
      nettingInsulatorStringLength: insulatorStringLength,
      nettingOtherLineComponents: otherLineComponents,
      multipleNettingCalculations: multipleNettings,
      nettingWidth: Math.max(...multipleNettings.map((item) => item.calculatedWidth || 0)),
      calculatedNettingLength: Math.max(...multipleNettings.map((item) => item.calculatedLength || 0)),
      insulband: {
        basicsParameter: {
          spanLength: initialCrossingPoint?.spanLength,
          designWindPressure: initialCrossingPoint?.designWindPressure || 0.5,
        },
        parametersWire: {
          conductorType: conductorType,
          outerDiameterMm: conductorSpec?.outerDiameterMm,
          weightPerMeterNPerM: conductorSpec?.weightPerMeterNPerM,
          conductorHorizontalTension: conductorHorizontalTension,
          insulatorStringLength: insulatorStringLength,
        },
        otherLineComponents,
        totalNettingDevicesWeight,
        multipleNettings,
      },
    };
    console.log("步骤13: 保存数据=", saveData);

    onUpdate(saveData);
    toast({ title: "保存成功", description: "绝缘绳网计算参数和结果已保存。" });
  }, [multipleNettings, onUpdate, otherLineComponents, conductorType, conductorHorizontalTension, insulatorStringLength, toast, conductorSpec, initialCrossingPoint]);

  const maxWindOffsetSource = useMemo(() => {
    console.log("步骤14: 确定最大风偏来源");
    const validWindOffsets = allWindOffsets.filter((r) => r.isValid);
    if (validWindOffsets.length === 0) {
      console.log("步骤14: 无有效风偏数据");
      return "N/A";
    }

    const maxItem = validWindOffsets.reduce(
      (max, current) =>
        parseFloat(current.windOffset) > parseFloat(max.windOffset)
          ? current
          : max,
      { windOffset: "-1" }
    );
    console.log(`步骤14: 最大风偏来源为 ${maxItem.name} (${maxItem.windOffset}m)`);
    return maxItem.name;
  }, [allWindOffsets]);

  // 步骤15: 计算所有绝缘绳网总重量
  const totalNettingDevicesWeight = useMemo(() => {
    console.log("步骤15: 计算所有绝缘绳网总重量");
    const total = multipleNettings.reduce((sum, netting) => {
      const {
        nettingInsulatorRodCount = 0,
        nettingInsulatorRodLength = 0,
        nettingInsulatorRodUnitWeight = 0,
        nettingRopeCount = 0,
        nettingRopeLength = 0,
        nettingRopeUnitWeight = 0,
        nettingAttachmentTotalWeight = 0,
      } = netting;

      const g = 9.8;
      const rodWeight =
        nettingInsulatorRodCount *
        nettingInsulatorRodLength *
        nettingInsulatorRodUnitWeight;
      const ropeWeight =
        nettingRopeCount * nettingRopeLength * nettingRopeUnitWeight;
      const totalKg = rodWeight + ropeWeight + nettingAttachmentTotalWeight;
      const weightN = totalKg * g;

      console.log(`步骤15: 绳网 ${netting.name} 重量=${weightN.toFixed(2)}N`);
      return sum + weightN;
    }, 0);
    console.log(`步骤15: 总重量=${total.toFixed(2)}N`);
    return total;
  }, [multipleNettings]);

  // 计算公式配置
  const formulas = [
    {
      name: "绝缘绳网宽度计算",
      description: "根据被跨越物宽度和交叉角度计算绳网所需宽度",
      formula: "BNet = (W / sin(α)) + 2 × bExtra",
      variables: [
        { symbol: "BNet", description: "绝缘绳网宽度", unit: "m" },
        { symbol: "W", description: "被跨越物宽度", unit: "m" },
        { symbol: "α", description: "交叉角度", unit: "度" },
        { symbol: "bExtra", description: "额外增加宽度（两侧）", unit: "m" },
      ],
      conditions: [
        "考虑线路与被跨越物的交叉角度",
        "额外增加宽度一般取2m，确保足够的安全余量",
        "当交叉角度接近90°时，有效宽度接近实际宽度",
      ],
      reference: "DL/T 5301-2013 附录C 封网装置选择计算",
    },
    {
      name: "导线风偏计算（简化）",
      description: "计算导线在风荷载作用下的最大横向位移",
      formula: "ZWind ≈ (ω₀ × d × 100) / (H / 1000)",
      variables: [
        { symbol: "ZWind", description: "最大风偏", unit: "m" },
        { symbol: "ω₀", description: "设计风压标准值", unit: "kN/m²" },
        { symbol: "d", description: "导线外径", unit: "m" },
        { symbol: "H", description: "导线水平张力", unit: "N" },
      ],
      conditions: [
        "这是简化估算公式，未考虑风速、风向等复杂因素",
        "实际风偏还与档距、导线特性、气象条件有关",
        "正式设计需根据 GB 50545 进行详细计算",
      ],
    },
    {
      name: "绝缘绳网长度计算",
      description: "考虑安全净距和风偏，计算绳网两侧延伸长度",
      formula: "LNet = 2 × (dSafe + ZWind + LExt)",
      variables: [
        { symbol: "LNet", description: "绝缘绳网总长度", unit: "m" },
        { symbol: "dSafe", description: "安全净距", unit: "m" },
        { symbol: "ZWind", description: "最大风偏", unit: "m" },
        { symbol: "LExt", description: "封网延伸长度", unit: "m" },
      ],
      conditions: [
        "安全净距根据电压等级确定，一般≥3.5m",
        "封网延伸长度一般取10m",
        "需确保在最不利工况下导线不接触封网",
      ],
      reference: "DL/T 5301-2013 附录C.3 封网装置绳索规格的确定",
    },
  ];

  return (
    <TooltipProvider>
      <FormulaDisplay
        standard="DL/T 5301-2013 输电线路工程架线施工工艺规程 附录C"
        formulas={formulas}
      />
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6">
        <div className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-lg">
                <Ruler className="w-4 h-4 text-blue-600" />
                共享基础参数
              </CardTitle>
              <CardDescription>
                这些参数将应用于下方所有的绝缘绳网计算
              </CardDescription>
            </CardHeader>
            <CardContent className="grid grid-cols-2 md:grid-cols-2 gap-4">
              <div>
                <Label className="text-xs">跨越档距 (m)</Label>
                <Input
                  value={crossingPoints[0]?.spanLength ?? 0}
                  readOnly
                  className="h-8 bg-slate-100 cursor-not-allowed border-slate-200"
                />
              </div>
              <div>
                <Label className="text-xs">设计风压 (kN/m²)</Label>
                <Input
                  value={crossingPoints[0]?.designWindPressure || 0.5}
                  readOnly
                  className="h-8 bg-slate-100 cursor-not-allowed border-slate-200"
                />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-lg">
                <Cable className="w-4 h-4 text-green-600" />
                共享导线参数
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <Label className="text-xs">导线型号</Label>
                  <Select
                    value={conductorType}
                    onValueChange={setConductorType}
                  >
                    <SelectTrigger className="h-8">
                      <SelectValue placeholder="请选择导线" />
                    </SelectTrigger>
                    <SelectContent>
                      {allConductorSpecs.map((spec) => (
                        <SelectItem key={spec.model} value={spec.model}>
                          {spec.model}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                {isLoadingConductorSpec ? (
                  <div className="text-sm text-gray-500 text-center py-2">
                    加载中...
                  </div>
                ) : !conductorSpec ? (
                  <div className="text-sm text-red-500 text-center py-2">
                    请选择有效型号
                  </div>
                ) : (
                  <div className="grid grid-cols-2 gap-2 text-xs text-center p-2 bg-slate-50 rounded">
                    <div>
                      <div className="text-gray-500">外径(mm)</div>
                      <div className="font-bold">
                        {conductorSpec.outerDiameterMm}
                      </div>
                    </div>
                    <div>
                      <div className="text-gray-500">单位重(N/m)</div>
                      <div className="font-bold">
                        {conductorSpec.weightPerMeterNPerM}
                      </div>
                    </div>
                  </div>
                )}
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label className="text-xs">水平放线张力 (N)</Label>
                  <Input
                    type="number"
                    step="1"
                    value={conductorHorizontalTension}
                    onChange={(e) =>
                      setConductorHorizontalTension(
                        parseFloat(e.target.value) || 0
                      )
                    }
                    className="h-8"
                  />
                </div>
                <div>
                  <Label className="text-xs">绝缘子串长 (m)</Label>
                  <Input
                    type="number"
                    step="0.1"
                    value={insulatorStringLength}
                    onChange={(e) =>
                      setInsulatorStringLength(parseFloat(e.target.value) || 0)
                    }
                    className="h-8"
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center justify-between text-lg">
                <div className="flex items-center gap-2">
                  <Zap className="w-4 h-4 text-orange-600" />
                  其他共享线路/绳索
                </div>
                <Button
                  onClick={addOtherLineComponent}
                  size="sm"
                  variant="outline"
                >
                  <Plus className="w-3 h-3 mr-1" />
                  添加
                </Button>
              </CardTitle>
            </CardHeader>
            <CardContent>
              {otherLineComponents.length === 0 ? (
                <div className="text-center py-4 text-gray-500 border border-dashed rounded-lg">
                  <p className="text-sm">暂无其他线路/绳索</p>
                </div>
              ) : (
                <div className="space-y-2">
                  {otherLineComponents.map((c) => (
                    <div
                      key={c.id}
                      className="border rounded p-2 bg-gray-50/50"
                    >
                      <div className="flex items-center justify-between mb-2">
                        <Input
                          value={c.name}
                          onChange={(e) =>
                            updateOtherLineComponent(
                              c.id,
                              "name",
                              e.target.value
                            )
                          }
                          className="h-7 text-sm font-medium flex-1 mr-2"
                        />
                        <Button
                          onClick={() => removeOtherLineComponent(c.id)}
                          size="icon"
                          variant="ghost"
                          className="w-6 h-6 text-red-500 hover:text-red-700"
                        >
                          <Trash2 className="w-3 h-3" />
                        </Button>
                      </div>
                      <div className="grid grid-cols-4 gap-2">
                        <div>
                          <Label className="text-xs">外径(mm)</Label>
                          <Input
                            type="number"
                            value={c.outerDiameter}
                            onChange={(e) =>
                              updateOtherLineComponent(
                                c.id,
                                "outerDiameter",
                                e.target.value
                              )
                            }
                            className="h-7"
                          />
                        </div>
                        <div>
                          <Label className="text-xs">重量(N/m)</Label>
                          <Input
                            type="number"
                            value={c.weightPerMeter}
                            onChange={(e) =>
                              updateOtherLineComponent(
                                c.id,
                                "weightPerMeter",
                                e.target.value
                              )
                            }
                            className="h-7"
                          />
                        </div>
                        <div>
                          <Label className="text-xs">串长(m)</Label>
                          <Input
                            type="number"
                            value={c.stringLength}
                            onChange={(e) =>
                              updateOtherLineComponent(
                                c.id,
                                "stringLength",
                                e.target.value
                              )
                            }
                            className="h-7"
                          />
                        </div>
                        <div>
                          <Label className="text-xs">张力(N)</Label>
                          <Input
                            type="number"
                            value={c.horizontalTension}
                            onChange={(e) =>
                              updateOtherLineComponent(
                                c.id,
                                "horizontalTension",
                                e.target.value
                              )
                            }
                            className="h-7"
                          />
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-sm">
                <Calculator className="w-4 h-4 text-purple-600" />
                封网装置总重汇总
              </CardTitle>
            </CardHeader>
            <CardContent className="text-center">
              <div className="text-2xl font-bold text-purple-800">
                {totalNettingDevicesWeight.toFixed(2)} N
              </div>
              <p className="text-xs text-gray-600 mt-1">
                所有 {multipleNettings.length} 个绝缘绳网的重量总和
              </p>
            </CardContent>
          </Card>
        </div>

        <div className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Maximize className="w-5 h-5 text-purple-600" />
                  绝缘绳网尺寸计算
                </div>
                <Button size="sm" onClick={addNettingObject}>
                  <Plus className="w-4 h-4 mr-2" />
                  添加绝缘绳网
                </Button>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              {multipleNettings.length === 0 ? (
                <div className="text-center py-8 text-gray-500 border border-dashed rounded-lg">
                  <p>请点击 "添加绝缘绳网" 开始计算</p>
                </div>
              ) : (
                multipleNettings.map((item, index) => {
                  // 为每个绝缘绳网项找到对应的跨越点数据
                  const correspondingCrossingPoint = crossingPoints[index] || null;
                  return (
                    <SingleNettingCalculator
                      key={item.id}
                      nettingItem={item}
                      onUpdate={updateNettingObject}
                      onRemove={removeNettingObject}
                      crossingPoint={initialCrossingPoint}
                      crossingPointData={correspondingCrossingPoint} // 传递对应的跨越点数据
                      scheme={scheme}
                      allWindOffsets={allWindOffsets}
                      index={index}
                    />
                  );
                })
              )}
            </CardContent>
          </Card>

          <div className="flex justify-end sticky bottom-4">
            <Button
              onClick={handleSave}
              className="bg-blue-600 hover:bg-blue-700 shadow-lg"
            >
              <Save className="w-4 h-4 mr-2" />
              保存所有计算结果
            </Button>
          </div>
        </div>
      </div>
    </TooltipProvider>
  );
}